﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class UtilFPS : MonoBehaviour {

	public Text outputGUIText;
	public float freq = 1;
	public float probeFPS = 0;
	string text = "XXX FPS";
	public int targetFPS = -1;
	public float timeScale = 1;
	public bool autoSpeedEnable = false;
	public float autoTimeScaleMin = 1;
	public float autoTimeScaleMax = 16;
	public float probeAutoTimeScale = 1;

	private IEnumerator loop() {
		while (true) {
			int f = Time.frameCount;
			float t = Time.realtimeSinceStartup;
			yield return new WaitForSeconds (1.0f/freq);
			int deltaf = Time.frameCount - f;
			float deltat = Time.realtimeSinceStartup - t;

			float fps = deltaf/deltat;
			text = fps.ToString("f2") + " FPS";
			outputGUIText.text = text;
			probeFPS = fps;

			if (probeFPS > 30.0f*1.25f) probeAutoTimeScale *= 1.01f;
			if (probeFPS < 30.0f/1.25f) probeAutoTimeScale /= 1.20f;
			probeAutoTimeScale = Mathf.Clamp (probeAutoTimeScale, autoTimeScaleMin, autoTimeScaleMax);

			Application.targetFrameRate = targetFPS;
			Time.timeScale = autoSpeedEnable ? probeAutoTimeScale : timeScale;
		}
	}

	void Start () {
			StartCoroutine (loop());	
	}

}
